﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="RestServiceCommandBase.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace RestClient
{
    using System.Net.Http;

    public abstract class RestServiceCommandBase<TServiceContext> : RestOperation where TServiceContext : class, IRestServiceContext
    {
        protected const string XmlContentType = "application/xml";

        protected RestServiceCommandBase(TServiceContext serviceContext) : base(serviceContext)
        {
        }

        protected RequestContext CreateGetOperationRequestContext()
        {
            var requestContext = new RequestContext
            {
                Method = HttpMethod.Get,
                Path = this.FormatPath(this.ServiceContext as TServiceContext)
            };

            this.AddParameters(requestContext);

            return requestContext;
        }

        protected RequestContext CreatePostOperationRequestContext()
        {
            var requestContext = new RequestContext
            {
                Method = HttpMethod.Post,
                Path = this.FormatPath(this.ServiceContext as TServiceContext),
                Body = this.FormatBody(),
                ContentType = this.GetContentType()
            };

            this.AddParameters(requestContext);

            return requestContext;
        }

        protected RequestContext CreateDeleteOperationRequestContext()
        {
            var requestContext = new RequestContext
            {
                Method = HttpMethod.Delete,
                Path = this.FormatPath(this.ServiceContext as TServiceContext)
            };

            this.AddParameters(requestContext);

            return requestContext;
        }

        protected RequestContext CreatePutOperationRequestContext()
        {
            var requestContext = new RequestContext
            {
                Method = HttpMethod.Put,
                Path = this.FormatPath(this.ServiceContext as TServiceContext),
                Body = this.FormatBody(),
                ContentType = this.GetContentType()
            };

            this.AddParameters(requestContext);

            return requestContext;
        }

        protected abstract string FormatPath(TServiceContext serviceContext);

        protected virtual string FormatBody()
        {
            return string.Empty;
        }

        protected virtual void AddParameters(RequestContext requestContext)
        {
        }

        protected virtual string GetContentType()
        {
            return XmlContentType;
        }
    }
}